package com.search.sevice.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.clients.FeginClient;
import com.hmall.common.dto.PageDTO;
import com.search.mapper.SearchMapper;
import com.search.pojo.Item;
import com.search.pojo.ItemDoc;
import com.search.pojo.RequestParams;
import com.search.sevice.ISearchService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class SearchService extends ServiceImpl<SearchMapper, Item> implements ISearchService {

    @Resource
    private RestHighLevelClient client;

    @Autowired
    FeginClient feginClient;

    SearchResponse response;

    @Override
    public List<String> finadAll(String key) {
        SearchRequest request = new SearchRequest("hmall");
        request.source().suggest(new SuggestBuilder().addSuggestion("suggestions",
                SuggestBuilders.completionSuggestion("suggestion")
                        .prefix(key)
                        .skipDuplicates(true).size(10)
        ));
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Suggest suggest = response.getSuggest();
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            return options.stream().map(Suggest.Suggestion.Entry.Option::getText).map(Text::toString).collect(Collectors.toList());
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Map<String, List<String>> filter(RequestParams params) {

        //1.创建搜索对象
        SearchRequest request = new SearchRequest("hmall");
        String key = params.getKey();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isNotBlank(key)) {
            //key 不为空 添加请求参数
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
        } else boolQueryBuilder.must(QueryBuilders.matchAllQuery());

        request.source().query(boolQueryBuilder);
        request.source().size(0);
        //品牌聚合
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(10)
        );
        // 分类聚合
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(10));
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            List<String> brandAgg = getAggByName(response.getAggregations(), "brandAgg");
            List<String> categoryAgg = getAggByName(response.getAggregations(), "categoryAgg");
            HashMap<String, List<String>> map = new HashMap<>();
            map.put("category", categoryAgg);
            map.put("brand", brandAgg);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public PageDTO<ItemDoc> search(RequestParams params) {
        SearchRequest request = new SearchRequest("hmall");
        baseQueryBuilder(params, request);

        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            return handleResponse(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void insertById(Long id) {
        try {
            // 0.根据id查询酒店数据
            Item item = getById(id);
            // 转换为文档类型
            ItemDoc itemDoc = new ItemDoc(item);

            // 1.准备Request对象
            IndexRequest request = new IndexRequest("hmall").id(item.getId().toString());
            // 2.准备Json文档
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("hmall", id.toString());
            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private PageDTO<ItemDoc> handleResponse(SearchResponse response) {
        SearchHits hits = response.getHits();
        long value = hits.getTotalHits().value;
        SearchHit[] hits1 = hits.getHits();

        ArrayList<ItemDoc> itemDocs = new ArrayList<>();
        for (SearchHit doc : hits1) {
            Map<String, HighlightField> highlightFields = doc.getHighlightFields();
            HighlightField highlightField = highlightFields.get("name");
            ItemDoc itemDoc = JSON.parseObject(doc.getSourceAsString(), ItemDoc.class);

            if (highlightField != null) {
                System.out.println(highlightField.fragments()[0].toString());
                itemDoc.setName(highlightField.fragments()[0].toString());
            }

            itemDocs.add(itemDoc);
        }
        return new PageDTO<ItemDoc>(value, itemDocs);
    }

    public void baseQueryBuilder(RequestParams params, SearchRequest request) {

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (StringUtils.isNotBlank(params.getKey())) {
            boolQuery.must(QueryBuilders.matchQuery("all", params.getKey()));
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("name");
//            highlightBuilder.preTags("<span style=\"color: red\">");
//            highlightBuilder.postTags("</span>");
            highlightBuilder.requireFieldMatch(false);
            request.source().highlighter(highlightBuilder);
        } else boolQuery.must(QueryBuilders.matchAllQuery());
        // 2.设置搜索条件
        if (StringUtils.isNotBlank(params.getBrand())) {
            System.out.println("brand: " + params.getBrand());
            boolQuery.must(QueryBuilders.matchQuery("brand", params.getBrand()));
//            boolQuery.filter(QueryBuilders.termQuery("brand",  params.getBrand()));
        }
        if (StringUtils.isNotBlank(params.getCategory())) {
            System.out.println("category: "+ params.getCategory());
            boolQuery.must(QueryBuilders.matchQuery("category", params.getCategory()));
//            boolQuery.filter(QueryBuilders.termQuery("brand",  params.getCategory()));
        }

        Integer page = params.getPage();
        Integer size = params.getSize();
        request.source().from((page - 1) * size).size(size);

        Long maxPrice = params.getMaxPrice();
        Long minPrice = params.getMinPrice();
        if (maxPrice != null && minPrice != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .gte((minPrice)*100)
                    .lte((maxPrice)*100)
            );
        }

        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(100) //算分函数得分
                        )
                }
        );

        if (params.getSortBy().equals("sold")){
            request.source().sort(SortBuilders.fieldSort(params.getSortBy()).order(SortOrder.DESC));
        }
        if (params.getSortBy().equals("price")){
            request.source().sort(SortBuilders.fieldSort(params.getSortBy()).order(SortOrder.DESC));
        }
        if (params.getSortBy().equals("commentCount")){
            request.source().sort(SortBuilders.fieldSort(params.getSortBy()).order(SortOrder.DESC));
        }
        request.source().query(functionScoreQueryBuilder);
    }

    public List<String> getAggByName(Aggregations aggregation, String name) {
        Terms aggregation1 = aggregation.get(name);
        List<? extends Terms.Bucket> buckets = aggregation1.getBuckets();
        List<String> list = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            Object key = bucket.getKey();
            list.add(key.toString());
        }
        return list;
    }

}
